﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using ArbolandiaBL;
using System.Xml;

public partial class _MyShoppingCart : System.Web.UI.Page
{
    public String updates = "[";
    protected void Page_PreLoad()
    {

    }

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            FillDrop();
            UpdateStep1(null, null);
        }
        LoadBanners();
    }
    protected void FillDrop()
    {
        //Fill shipping drop
        XmlDocument xml = new XmlDocument();
        xml.Load(MapPath("templates/shipping.xml"));
        var shippingList = Utilities.DeserializeObject<shipping>(xml.InnerXml);
        foreach (var item in shippingList.price)
        {
            drpShippingMethod.Items.Add(new ListItem()
            {
                Text = item.text,
                Value = item.value.ToString()
            });
        }
        drpShippingMethod.DataBind();
    }
    protected void UpdateStep1(object sender, EventArgs e)
    {
        Decimal total = 0;
        Decimal subtotal = 0;
        Decimal tax = 0;
        Decimal quantity = 0;

        var items = new List<String>();
        //if (HttpContext.Current.Session["arbolandiacart"] == null || ((List<String>)HttpContext.Current.Session["arbolandiacart"]).Count < 2)
        //{
        //    HttpContext.Current.Session["arbolandiacart"] = new List<String>();
        //    ((List<String>)HttpContext.Current.Session["arbolandiacart"]).Add("35|6|100");
        //    ((List<String>)HttpContext.Current.Session["arbolandiacart"]).Add("36|5|3");
        //}

        if (HttpContext.Current.Session["arbolandiacart"] != null)
        {
            HttpContext.Current.Session["arbolandiacart"] = HttpContext.Current.Session["arbolandiacart"];

            items = ((List<String>)HttpContext.Current.Session["arbolandiacart"]);

            for (int i = 0; i < items.Count; i++)
            {
                var detail = new ServiceUI().GetProductPriceDetail(Int32.Parse(items[i].Split('|')[1]), Int32.Parse(items[i].Split('|')[0]));
                quantity = Decimal.Parse(items[i].Split('|')[2]);
                total += detail.Price * quantity;


                var div = new HtmlGenericControl("div");
                div.Attributes.Add("class", "item");
                //div.InnerText = items[i].Split('|')[1];

                //Image
                var divImg = new HtmlGenericControl("div");
                divImg.Attributes.Add("class", "product-img");
                var img = new Image();
                img.Width = Unit.Percentage(100);
                img.Height = Unit.Percentage(100);

                img.ImageUrl = "http://dataclinicc.web709.discountasp.net/arb/imagessite/notavaible.jpg";
                img.ImageUrl = detail.ImageUrlThumnail;
                divImg.Controls.Add(img);
                div.Controls.Add(divImg);

                //Text
                var divText = new HtmlGenericControl("div");
                divText.Attributes.Add("class", "text");
                var divTextTitle = new HtmlGenericControl("div");
                divTextTitle.Attributes.Add("class", "title");
                divTextTitle.InnerText = detail.ProductCode;
                divText.Controls.Add(divTextTitle);
                var divTextDesc = new HtmlGenericControl("div");
                divTextDesc.Attributes.Add("class", "desc");
                divTextDesc.InnerText = detail.Description;
                divText.Controls.Add(divTextDesc);
                div.Controls.Add(divText);

                //Quantity
                var divQuantity = new HtmlGenericControl("div");
                divQuantity.Attributes.Add("class", "quantity");
                var divQuantityText = new Label();
                divQuantityText.Attributes.Add("class", "quantitytext");
                divQuantityText.Text = "Cantidad: ";
                divQuantity.Controls.Add(divQuantityText);
                var divQuantityInput = new TextBox();
                divQuantityInput.Text = items[i].Split('|')[2];
                divQuantityInput.ID = "input_" + items[i].Split('|')[1];
                divQuantityInput.MaxLength = 4;
                divQuantityInput.Attributes.Add("class", "input");
                divQuantityInput.Attributes.Add("readonly", "readonly");

                //divQuantityInput.Attributes.Add("onkeypress", "return validate(this);");
                divQuantity.Controls.Add(divQuantityInput);
                div.Controls.Add(divQuantity);

                //Price
                var divPrice = new HtmlGenericControl("div");
                divPrice.Attributes.Add("class", "price");
                divPrice.InnerText = detail.Price.ToString("C") + " pesos";
                div.Controls.Add(divPrice);

                //Delete
                var divDelete = new LinkButton();
                divDelete.Attributes.Add("class", "delete");
                divDelete.Text = "Eliminar";
                divDelete.OnClientClick = "del('" + items[i] + "', this, document.getElementById(\"" + drpShippingMethod.ClientID + "\").value); return false;";
                div.Controls.Add(divDelete);

                itemsContainer.Controls.Add(div);

                updates += "(document.getElementById(\'" + divQuantityInput.ClientID + "\') ? ";
                updates += "\"" + items[i].Split('|')[0] + "|" +
                                  items[i].Split('|')[1] + "|" +
                                  "\" + document.getElementById(\'" + divQuantityInput.ClientID + "\').value" +
                                  "";
                updates += " : \"\"),";
            }
            updates = updates.Substring(0, updates.Length - 1);
            updates += "]";

            if (items.Count > 0)
            {
                //var update = new LinkButton();
                //update.Attributes.Add("class", "update");
                //update.Text = "Actualizar";
                //update.OnClientClick = "upd(this, document.getElementById(\"" + drpShippingMethod.ClientID + "\").value); return false;";
                //itemsContainer.Controls.Add(update);

                subtotal = total;
                tax = (Decimal.Parse("0.00"));
                Decimal shipping; Decimal.TryParse(drpshippingValue.Value, out shipping);
                total += shipping;

                //lblSubtotal.Text = "$" + String.Format("{0:0.00}", subtotal) + " MXN";
                //lblTax.Text = "$" + String.Format("{0:0.00}", tax) + " MXN";
                //lblTotal.Text = "$" + String.Format("{0:0.00}", total) + " MXN";

                lblSubtotal.Text = subtotal.ToString("C") + " MXN";
                lblTax.Text = tax.ToString("C") + " MXN";
                lblTotal.Text = total.ToString("C") + " MXN";

            }
        }
    }
    protected void drpCategories_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void LoadBanners()
    {
        var banner1 = new ServiceUI().GetBanner(BannerType.Top);
        for (int i = 0; i < banner1.Count(); i++)
        {
            var c = new HyperLink() { ImageUrl = banner1[i].Url, NavigateUrl = banner1[i].LinkUrl };
            var p = new HyperLink() { NavigateUrl = banner1[i].LinkUrl, Text = ((i + 1)).ToString() };
            c.Target = "_blank";
            p.Attributes.Add("rel", ((i + 1)).ToString());
            imagereel.Controls.Add(c);
            paging.Controls.Add(p);
        }
        var banner2 = new ServiceUI().GetBanner(BannerType.Middle);
        for (int i = 0; i < banner2.Count(); i++)
        {
            var c = new HyperLink() { ImageUrl = banner2[i].Url, NavigateUrl = banner2[i].LinkUrl };
            var p = new HyperLink() { NavigateUrl = banner2[i].LinkUrl, Text = ((i + 1)).ToString() };
            c.Target = "_blank";
            p.Attributes.Add("rel", ((i + 1)).ToString());
            imagereel2.Controls.Add(c);
            paging2.Controls.Add(p);
        }
        var banner3 = new ServiceUI().GetBanner(BannerType.Bottom);
        for (int i = 0; i < banner3.Count(); i++)
        {
            var c = new HyperLink() { ImageUrl = banner3[i].Url, NavigateUrl = banner3[i].LinkUrl };
            var p = new HyperLink() { NavigateUrl = banner3[i].LinkUrl, Text = ((i + 1)).ToString() };
            c.Target = "_blank";
            p.Attributes.Add("rel", ((i + 1)).ToString());
            imagereel3.Controls.Add(c);
            paging3.Controls.Add(p);
        }
    }

    [System.Web.Services.WebMethod(true)]
    public static String Del(String item, String shipping)
    {
        try
        {
            var items = ((List<String>)HttpContext.Current.Session["arbolandiacart"]);
            if (items.Remove(item))
            {
                Decimal total = 0;
                for (int i = 0; i < items.Count; i++)
                {
                    var detail = new ServiceUI().GetProductPriceDetail(Int32.Parse(items[i].Split('|')[1]), Int32.Parse(items[i].Split('|')[0]));
                    var quantity = Decimal.Parse(items[i].Split('|')[2]);
                    total += detail.Price * quantity;
                }

                var subtotal = (total);
                var tax = (Decimal.Parse("0.00"));

                total += Decimal.Parse(shipping);
                if (items.Count() <= 0) { total = 0; }
                HttpContext.Current.Session["arbolandiacart"] = items;

                return "$" + String.Format("{0:0.00}", subtotal) + " MXN" + "|"
                     + "$" + String.Format("{0:0.00}", tax) + " MXN" + "|"
                     + "$" + String.Format("{0:0.00}", total) + " MXN";


            }
            else
            {
                throw new Exception("Error al eliminar el elemento");
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

    [System.Web.Services.WebMethod(true)]
    public static String Upd(string itemsupdstr, String shipping)
    {
        try
        {
            //List<String> itemsupd = Utilities.DesSerializeJson<List<string>>(itemsupdstr);
            //HttpContext.Current.Session["arbolandiacart"] = itemsupd;

            var items = ((List<String>)HttpContext.Current.Session["arbolandiacart"]);
            Decimal total = 0;
            for (int i = 0; i < items.Count; i++)
            {
                if (items[i] != "")
                {
                    var detail = new ServiceUI().GetProductPriceDetail(Int32.Parse(items[i].Split('|')[1]), Int32.Parse(items[i].Split('|')[0]));
                    var quantity = Decimal.Parse(items[i].Split('|')[2]);
                    total += detail.Price * quantity;
                }
            }

            var subtotal = total;
            var tax = (Decimal.Parse("0.00"));

            total += Decimal.Parse(shipping);

            //return "$" + String.Format("{0:0.00}", subtotal) + " MXN" + "|"
            //     + "$" + String.Format("{0:0.00}", tax) + " MXN" + "|"
            //     + "$" + String.Format("{0:0.00}", total) + " MXN";

            return subtotal.ToString("C") + " MXN" + "|"
                 + tax.ToString("C") + " MXN" + "|"
                 + total.ToString("C") + " MXN";
        }
        catch (Exception)
        {
            throw;
        }
    }

    [System.Web.Services.WebMethod(true)]
    public static void SaveInfo(String jsonData, String shipping)
    {
        try
        {
            //HttpContext.Current.Session["arbolandiacart"] = itemsupd;
            Guid customerGuid = Guid.NewGuid();
            var order = new ArbolandiaBL.Orders();
            var items = ((List<String>)HttpContext.Current.Session["arbolandiacart"]);
            //Obtenemos todos los productos a comprar
            var jsonProds = new List<Utilities.OrderJson>();
            Decimal total = 0;
            for (int i = 0; i < items.Count; i++)
            {
                if (items[i] != "")
                {
                    var product = new Utilities.OrderJson();
                    var detail = new ServiceUI().GetProductPriceDetail(Int32.Parse(items[i].Split('|')[1]), Int32.Parse(items[i].Split('|')[0]));
                    product.productDetailId = detail.Id;
                    product.productId = Int32.Parse(items[i].Split('|')[0]);
                    product.quantity = Int32.Parse(items[i].Split('|')[2]);
                    product.amount = detail.Price * product.quantity;
                    total += product.amount;
                    jsonProds.Add(product);
                }
            }
            order.CustomerGuid = customerGuid;


            var subtotal = (total);
            var tax = (Decimal.Parse("0.00"));

            total += Decimal.Parse(shipping);
            order.SubTotal = subtotal;
            order.Total = total;
            order.Iva = tax;
            order.Otros = Decimal.Parse(shipping);
            //Parseamos el jsonProds
            var stringJson = Utilities.SerializeToJson<List<Utilities.OrderJson>>(jsonProds);
            order.OrderFullJson = stringJson;
            order.Estaus = Utilities.STATUS_1;
            order.iEstaus = 1;
            order.OrderGuid = Guid.NewGuid();
            order.SystemDate = DateTime.Now;
            HttpContext.Current.Session["customerGuidId"] = order.CustomerGuid;
            HttpContext.Current.Session["orderGuidId"] = order.OrderGuid;
            var customer = new ArbolandiaBL.Customer();
            ClientForm cli = Utilities.DesSerializeJson<ClientForm>(jsonData);
            if (cli != null)
            {
                customer.CustomerGuid = customerGuid;
                customer.CompanyName = cli.Company;
                customer.Email = cli.Email;
                customer.Names = cli.Name;
                customer.LastNames = cli.LastName;
                customer.MobilePhoneNumber = cli.Phone;
                customer.Active = false;
                customer.CreatedOnUtc = DateTime.Now;
                customer.LastActivityDate = DateTime.Now;
                var address = new ArbolandiaBL.CustomerAddress();
                address.FullAddress = cli.Address1 + "  " + cli.Address2;
                address.Country = cli.Country;
                address.City = cli.City;
                address.State = cli.State;
                address.ZipCode = cli.ZipCode;
                address.CustomerGuid = customerGuid;
                new UIShoppingCart().SaveShopping(order, customer, address);
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

    [System.Web.Services.WebMethod(true)]
    public static String ChangeSt(Int32 status)
    {
        var res = "0.00";
        try
        {
            if (HttpContext.Current.Session["customerGuidId"] != null)
            {
                var shoppingCart = new UIShoppingCart();
                var customer = (Guid)HttpContext.Current.Session["customerGuidId"];
                var order = (Guid)HttpContext.Current.Session["orderGuidId"];
                var guid = (Guid)HttpContext.Current.Session["customerGuidId"];
                shoppingCart.ChangeStatus(guid, (short)status);
                shoppingCart.SendEmail(customer, order);
                HttpContext.Current.Session["customerGuidId"] = null;
                HttpContext.Current.Session["orderGuidId"] = null;
                HttpContext.Current.Session["arbolandiacart"] = null;
                var ord = shoppingCart.GetOrder(order);
                res = ord.Total.ToString();
            }
        }
        catch (Exception)
        {
            throw;
        }
        return res;
    }

    [System.Web.Services.WebMethod(true)]
    public static String ChangeStatus(Int32 status)
    {
        var res = "0.00";
        try
        {
            if (HttpContext.Current.Session["customerGuidId"] != null)
            {
                var shoppingCart = new UIShoppingCart();
                var customer = (Guid)HttpContext.Current.Session["customerGuidId"];
                var order = (Guid)HttpContext.Current.Session["orderGuidId"];
                var guid = (Guid)HttpContext.Current.Session["customerGuidId"];
                shoppingCart.ChangeStatus(guid, (short)status);
                shoppingCart.SendEmail(customer, order);
                HttpContext.Current.Session["customerGuidId"] = null;
                HttpContext.Current.Session["orderGuidId"] = null;
                HttpContext.Current.Session["arbolandiacart"] = null;
                var ord = shoppingCart.GetOrder(order);
                res = ord.Total.ToString();

            }
            return res;
        }
        catch (Exception)
        {

            throw;
        }

    }

    public class ClientForm
    {
        public string Name { get; set; }
        public string LastName { get; set; }
        public string Company { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public string ZipCode { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
        public string Fax { get; set; }
    }

    protected void drpShippingMethod_SelectedIndexChanged(object sender, EventArgs e)
    {
        UpdateStep1(null, null);
    }
}